<?php

namespace Api\Controller;

use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Validator\Authentication;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Validator\File\UploadFile;
use Zend\View\Model\ViewModel;
use Admin\Model\AdminUser;
use \Velacolib\Utility\Utility;
use Zend\Form\Form;
use Zend\Form\Element;
use Zend\Db\Adapter\Driver\DriverInterface;
use Admin\Model\AdminUserContact;

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');
class RegisterController extends AbstractActionController {

    public function onDispatch(\Zend\Mvc\MvcEvent $e)
    {
        $this->layout('frontend/layout');
        return parent::onDispatch($e);
    }
    public function indexAction(){

    }
    public function registerAction()
    {
        $response['result'] = false;
        $response['register'] = false;
        $response['user_id'] = null;

        //Ajax function
        if ($this->getRequest()->isPost()) {

            $dataSubmit = $this->params()->fromPost();

            //Check if ajax request is submited

            if (!isset ($dataSubmit['ajax_request']))

                $this->redirect("/");

            $user_model = new AdminUser();

            $validate = $user_model->validateUserFields($dataSubmit);

            if ($validate['pass']) {

                $dataSubmit['name'] = $this->params()->fromPost('f_name') . ' ' . $this->params()->fromPost('l_name');

                $dataSubmit['status'] = '1';

                $dataSubmit['user_type'] = '2';

                $time = time();

                $dataSubmit['time_reg'] = $time;
                $password = $dataSubmit['password'];
                if($dataSubmit['avatar'] == '') $dataSubmit['avatar'] = '/img/upload/user_temp/person-avatar.png';

                $dataSubmit['password'] = md5($dataSubmit['email'] . $dataSubmit['password']);


                unset ($dataSubmit['f_name'], $dataSubmit['l_name'], $dataSubmit['r_password']);

                $object = Utility::UserGateway('Admin\Model\AdminUserTable')->getUserByEmail($dataSubmit['email']);

                if (is_object($object)) {

                    $response['result'] = false;

                    $response['message'] = 'Email này đã có người sử dụng';

                } else {
                    $array_contact = array();
                    if(isset($dataSubmit['contact'])){
                        $array_contact = $dataSubmit['contact'];
                        unset($dataSubmit['contact']);
                    }

                    $user_model->exchangeArray($dataSubmit);
                    $addUser = Utility::UserGateway('Admin\Model\AdminUserTable')->saveUser($user_model);

                    $user_table = Utility::UserGateway('Admin\Model\AdminUserTable');
                    $data['username'] = $dataSubmit['email'];
                    $data['password'] =    $password;


                    if ($addUser) {
                        foreach($array_contact as $key => $values){

                            foreach($values as $value){
                                $adminuserContact = new AdminUserContact();
                                $adminuserContact->user_id = $addUser;
                                $adminuserContact->contact_type = $key;
                                $adminuserContact->contact_value = $value;
                                Utility::UserGateway('Admin\Model\AdminUserContactTable')->saveUserContact($adminuserContact);
                            }
                        }

                        $user_table->setLoginUser($data);
                        $login_obj = new AuthenticationService(null, $user_table)   ;
                        $login_obj->authenticate();


                        $response['result'] = true;


                        $response['message'] = 'Đăng ký thành công!';
                        $response['register'] = true;
                        $response['user_id'] =   Utility::UserGateway('Admin\Model\AdminUserTable')->getLastIdInsert();

                        //sending email verify to user register
                        $smtp_option = array(
                            'smtp_user' => 'mrhungmaster1905@gmail.com',
                            'smtp_password' => '`1qa2ws#ED'
                        );
                        $senderInfo = array(
                            'email' => 'mrhungmaster1905@gmail.com',
                            'name' => 'VelaCo'

                        );

                        $RecipientInfo = array(
                            'email' => $dataSubmit['email'],
                            'name' => $dataSubmit['name'],
                            'link' => 'http://' . $_SERVER['HTTP_HOST'] . '/user/verify/' . $time,
                        );

                        $template_path = 'admin/email/tpl/template';

                        $subject = 'Email Verify';

                        Utility::SendMail(false, $smtp_option, $senderInfo, $RecipientInfo, $template_path, $subject);

                    } else $response['message'] = 'Không thể đăng ký người dùng mới';
                }


            } else $response['message'] = $validate['message'];
        } else $response['message'] = 'Method not allowed';
       // header("ContentType: application/json");
        echo json_encode($response);
        die();
    }


    public function userimagesAction(){
        $result['upload'] = "0";
        $file_type = $_FILES['file']['type'];
        if (!strstr ($file_type, 'image'))
            $result['message'] = 'Định dạng không đúng, chỉ chấp nhận file ảnh!';
        else{
            $target = $_SERVER['DOCUMENT_ROOT'] . '/img/upload/user_temp/' . $_FILES['file']['name'];
            $upload = move_uploaded_file($_FILES['file']['tmp_name'], $target);
            if ($upload){
                $imageUrl = '/img/upload/user_temp/' . $_FILES['file']['name'];
                $result['upload'] = "1";
                $result['img_url'] = $imageUrl;
                $result['message'] = 'Upload thành công';
            }
            else $result['message'] = 'Có lỗi trong quá trình xử lý, xin vui lòng thử lại';
        }
        header ('ContentType: application/json');
        echo json_encode($result);
        die();
    }


    public function fbAction(){
        $post = $this->params()->fromPost('data');
        $fb_picture = "https://graph.facebook.com/".$post['id']."/picture";

        $user_save = array(
            'name' => $post['first_name'].' '.$post['last_name'],
            'email' => $post['email'],
            'avatar' => $fb_picture,
            'time_reg'=>time(),
            'user_type'=>2,
            'confirm'=>1
        );
        /*
         * insert user into userTable
         */

        $userTalbe = new AdminUser();
        $userModel = Utility::UserGateway("Admin\Model\AdminUserTable");

        // check true /false email
        $email =  $userModel->getUserByEmail($user_save['email']);

        if(is_object($email)){
            // authenticate
            $login_user['username'] = $user_save['email'];

            $userModel->setLoginUser($login_user);

            $login_obj = new AuthenticationService(null, $userModel);

            $login_obj->authenticate();
            $response['result'] = true;
            $response['message'] = 'Login success!';
            $response['user_info'] = $login_obj->getIdentity();


        }else{
            // add user inti db
            $userTalbe->exchangeArray($user_save);

            $userModel->saveUser($userTalbe);

            // authenticate

            $login_user['username'] = $user_save['email'];

            $userModel->setLoginUser($login_user);

            $login_obj = new AuthenticationService(null, $userModel);

            $login_obj->authenticate();

            $response['result'] = true;
            $response['message'] = 'Login success!';
            $response['user_info'] = $login_obj->getIdentity();
        }
        echo json_encode($response);
        die;
    }

    /*
     * validate data
     * $_post data as array
     * */
    public function validateAction(){
        $validate = $this->params()->fromPost();
        if(isset($validate['email'])){
            if(!filter_var($validate['email'], FILTER_VALIDATE_EMAIL)) {
               echo false;die;
            }
        }
        $userModel = Utility::UserGateway('Admin\Model\AdminUserTable');
        $data =  $userModel->getUserWhere($validate);
        if(count($data) > 0){
            echo true;   die;
        }else{
            echo false; die;
        }

    }

}